package qj.tool.gae;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import qj.util.ReflectUtil;
import qj.util.funct.F0;
import qj.util.funct.F2;

public class Paging<A> {

	public int from = 0;
	public Integer total = null;
	public int pageSize;
	public F2<Integer, Integer, List<A>> listF;
	public F0<Integer> totalF;
	
	public static String defaultPageParam = "pageNo";
	
	public String pageParam = defaultPageParam;
	
	public static <A> Paging<A> create(int pageSize, F2<Integer,Integer,List<A>> listF, F0<Integer> totalF) {
		Paging<A> paging = new Paging<A>();
		paging.pageSize = pageSize;
		paging.listF = listF;
		paging.totalF = totalF;
		return paging;
	}
	
	public Page<A> page(Object page) {
		int from = this.from;
		if (page instanceof HttpServletRequest) {
			page = ((HttpServletRequest)page).getParameter(pageParam);
		}
		if (page == null) {
		} else if (page instanceof String) {
			if (page.equals("first")) {
				from = 0;
			} else if (page.equals("last")) {
				total = totalF.e();
				from = (total/pageSize) * pageSize;
			} else {
				from = Integer.parseInt((String)page) * pageSize;
			}
		} else if (page instanceof Integer) {
			from = ((Integer)page) * pageSize;
		}
		
		Page<A> p = new Page<A>();
		ReflectUtil.copy(p, this);
		p.from = from;
		return p;
	}
}
